﻿using System.ComponentModel;
using System.Threading.Tasks;
using DGZImp.Core.Services;
using DGZImp.MdsProject.Base;
using DGZImp.MdsProject.Devices.Base;
using DGZImp.MdsProject.Devices.Helper;
using DGZImp.MdsProject.Devices.Models;
using DGZImp.MdsProject.Models;
using DGZImp.MdsProject.Services;
using Microsoft.Extensions.DependencyInjection;
using Nomad.Iot;

namespace DGZImp.MdsProject.Devices
{
    /// <summary>
    /// 对接机构
    /// </summary>
    public class Connector : PlcDevice<ConnectorData>
    {
        public Connector(string id, string name, IIotServe serve, List<PlcDataMapItem> maps) : base(id, name, serve, maps)
        {
            OnDataChange += OnConnectorDataPropertyChanged;
        }

        [MdsAction("发送命令", "直接发送指令")]
        public async Task<OperateResult> SendCommandAsync([MdsParameter("指令")] ConnectorCommandEnum Command)
        {
            return await WriteDataToPlc(new List<PlcDataWriteItem> {
                new(){ PropName = nameof(ConnectorData.Command), Value = Command }
            });
        }

        private async void OnConnectorDataPropertyChanged(object sender)
        {
            //无出罐信号
            if (Data.TankShipOut != ConnectorShipOutEnum.出罐) return;
            //有出罐信号但实际无货
            if (Data.IsFull != GoodsStatusEnum.有货) return;
            //上对接产生取空罐信号, 下对接 完成生产后 出料至下一工序
            try
            {
                var service = AutofacContainerModule.GetService<Mds_LogisticTaskService>();
                await service.ProcessConnectorTankTask(Id);
            }
            catch (Exception ex)
            {
                SysLogger.LogError(ex, "处理出罐信号异常");
            }
        }
    }

    public class ConnectorData
    {
        [Description("00.编号")]
        public int ConnectorNo { get; set; }
        [Description("01.心跳")]
        public int Heartbeat { get; set; }

        [Description("02.状态")]
        public ConnectorStatus Status { get; set; }

        [Description("03.事件")]
        public ConnetorEventCode EventCode { get; set; }

        [Description("04.光电遮挡")]
        public GoodsStatusEnum IsFull { get; set; }

        [Description("05.取放货地址")]
        public int Station { get; set; }

        [Description("06.任务号")]
        public int TaskNo { get; set; }

        [Description("07.出罐信号")]
        public ConnectorShipOutEnum TankShipOut { get; set; }

        [Description("08.错误码")]
        public ConnectorErrorEnum Error { get; set; }

        [Description("09.上位机故障")]
        public int MCSError { get; set; }

        [Description("10.当前对接动作")]
        public ConnectorCommandEnum OperationCmd { get; set; }

        [Description("80.写入指令")]
        public ConnectorCommandEnum Command { get; set; }

        [Description("99.刷新时间")]
        public string RefreshTime { get; set; }
    }
}
